package bjtu.cit.bookshop.common;

import bjtu.cit.bookshop.entities.Book;
import bjtu.cit.bookshop.service.IBookService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jia19 on 2015/10/29.
 */
public class ShoppingCart {

    public class CartBook {
        private String name;
        private int bookId;
        private int num;
        private BigDecimal price;

        public BigDecimal getPrice() {
            return price;
        }

        public void setPrice(BigDecimal price) {
            this.price = price;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public CartBook(int bookId, int num) {
            this.bookId = bookId;
            this.num = num;
        }

        public int getNum() {
            return num;
        }

        public void setNum(int num) {
            this.num = num;
        }

        public int getBookId() {
            return bookId;
        }

        public void setBookId(int bookId) {
            this.bookId = bookId;
        }

        @Override
        public boolean equals(Object o) {
            if (o instanceof CartBook) {
                if (((CartBook) o).bookId == this.bookId) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }

    }

    private List<CartBook> list = new ArrayList<CartBook>();

    public void addBook(int id, int num) {
        CartBook cartBook = new CartBook(id, num);
        int index = 0;
        if ((index = list.indexOf(cartBook)) >= 0) {
            cartBook = list.get(index);
            cartBook.setNum(cartBook.getNum() + num);
        }
        else {
            list.add(cartBook);
        }

    }

    public void delBook(int id) {
        CartBook cartBook = new CartBook(id, 0);
        if (list.contains(cartBook)) {
            list.remove(cartBook);
        }
    }

    public void changeNum(int id, int num) {
        CartBook cartBook = new CartBook(id, num);
        int index;
        if ((index = list.indexOf(cartBook)) >= 0) {
            cartBook = list.get(index);
            cartBook.setNum(num);
        }
    }

    public List<CartBook> getBookList() {
        return list;
    }

    public void removeAll() {
        list.clear();
    }

}
